/*
 * Copyright (c) 2020, 2025, keyila All rights reserved.
 *
 */
package com.clp.util;

import com.clp.exception.ShareLockException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author clp
 * @version 1.0
 */
@Component
public class RedisShareLockUtil {

    @Resource
    private RedisUtil redisUtil;

    private Long OUT_TIME=1000L;

    /**
     * 加锁
     * **/

    public boolean lock(String lockKey, String requestId,Long time){
        if (StringUtils.isBlank(lockKey) || StringUtils.isBlank(requestId) || time<=0){
            throw new ShareLockException("分布式锁-加锁-参数异常");
        }
        long currentTime=System.currentTimeMillis();
        long outTime=currentTime+OUT_TIME;
        Boolean result=false;
        while (currentTime<outTime){
            //使用Redis的SetNx进行加锁
            result=redisUtil.setNx(lockKey,requestId,time, TimeUnit.MILLISECONDS);
            if (result){
                return result;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentTime=System.currentTimeMillis();
        }
        return result;
    }
    /**
     * 解锁
     * **/

    public boolean unLock(String lockKey, String requestId){
        if (StringUtils.isBlank(lockKey) || StringUtils.isBlank(requestId)){
            throw new ShareLockException("分布式锁-解锁-参数异常");
        }
        try {
            String value = redisUtil.get(lockKey);
            if (value.equals(requestId)){
                redisUtil.del(lockKey);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 尝试加锁
     * **/

    public boolean tryLock(String lockKey, String requestId,Long time){
        if (StringUtils.isBlank(lockKey) || StringUtils.isBlank(requestId) || time<=0){
            throw new ShareLockException("分布式锁-尝试加锁失败-参数异常");
        }
        return redisUtil.setNx(lockKey,requestId,time,TimeUnit.MILLISECONDS);
    }

}
